/*
 * @lc app=leetcode.cn id=230 lang=typescript
 *
 * [230] 二叉搜索树中第K小的元素
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function kthSmallest(root: TreeNode | null, k: number): number {
    const res: any = [];
    while (root !== null || res.length) {
        while (root !== null) {
            res.push(root);
            root = root.left;
        }
        root = res.pop();
        k = k - 1;
        if (k === 0) {
            break;
        }
        root = root.right;
    }

    // console.log(res);
    return root.val;
};
// @lc code=end

